import { Button, Form, Input, Select, Space, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import { formatDate, formatMoney } from "../../../utils";
import { useAntdTable } from "ahooks";
import api from "../../../api";
import type { Order } from "../../../types/api";
import { useRef } from "react";
import CreateOrder from "./components/CreateOrder";
import { message, modal } from "../../../utils/AntdGlobal";
import OrderMarker from "./components/OrderMarker";
import OrderRoute from "./components/OrderRoute";

export default function OrderList() {
    const [form] = Form.useForm()
    const orderRef = useRef<any>(null)
    const markerRef = useRef<any>(null)
    const routeRef = useRef<any>(null)

    const getTableData = async ({ current, pageSize }: { current: number, pageSize: number }, formData: Order.SearchParams) => {
        return await api
            .getOrderList({
                ...formData,
                pageNum: current,
                pageSize
            })
            .then(
                data => {
                    return {
                        total: data.page.total,
                        list: data.list
                    }
                }
            )
    };
    const { tableProps, search } = useAntdTable(getTableData, {
        form,
        defaultPageSize: 10
    });

    const handleCreate = () => {
        orderRef.current?.open('create')
    }

    const handleDelete = (id: string) => {
        modal.confirm({
            title: "删除确认",
            content: <span>确认删除该订单吗？</span>,
            onOk: () => {
                handleOrderDelSubmit(id)
            }
        })
    }
    const handleOrderDelSubmit = async (id: string) => {
        await api.deleteOrder({ _id: id })
        message.success('删除成功')
        search.submit()
    }

    const handleDownload = async () => {
        await api.exportFile(form.getFieldsValue())
    }

    const handleMarker = (orderId: string) => {
        markerRef.current?.open(orderId)
    }

    const handleRoute = (orderId: string) => {
        routeRef.current?.open(orderId)
    }
    const columns: ColumnsType<Order.OrderItem> = [
        {
            title: "订单编号",
            dataIndex: 'orderId',
            key: "orderId",
            align: 'center'
        },
        {
            title: "城市",
            dataIndex: 'cityName',
            key: "cityName",
            align: 'center'
        },
        {
            title: "下单地址",
            dataIndex: 'startAddress',
            align: 'center',
            render(_, record) {
                return `${record.startAddress} - ${record.endAddress}`
            }
        },
        {
            title: "下单时间",
            dataIndex: 'createTime',
            key: "createTime",
            align: 'center',
            render(createTime: string) {
                return formatDate(createTime)
            }
        },
        {
            title: "订单价格",
            dataIndex: 'orderAmount',
            key: "orderAmount",
            align: 'center',
            render(orderAmount: string) {
                return formatMoney(orderAmount)
            }
        },
        {
            title: "订单状态",
            dataIndex: 'state',
            key: "state",
            align: 'center',
            render(state: number) {
                return {
                    1: '进行中',
                    2: '已完成',
                    3: '超时',
                    4: '取消'
                }[state]
            }
        },
        {
            title: "用户名称",
            dataIndex: 'userName',
            key: "userName",
            align: 'center'
        },
        {
            title: "司机名称",
            dataIndex: 'driverName',
            key: "driverName",
            align: 'center'
        },
        {
            title: "操作",
            key: "action",
            width: 200,
            align: 'center',
            render(_, record) {
                return (
                    <Space>
                        <Button type="text" onClick={() => handleMarker(record.orderId)} >打点</Button>
                        <Button type="text" onClick={() => handleRoute(record.orderId)} >轨迹</Button>
                        <Button type="text" danger onClick={() => handleDelete(record._id)}>删除</Button>
                    </Space>
                )
            }
        },
    ]




    return (
        <>
            <Form form={form} className="search" layout='inline' initialValues={{ state: 1 }}>
                <Form.Item name='orderId' label='订单ID'>
                    <Input placeholder='请输入订单ID' />
                </Form.Item>
                <Form.Item name='userName' label='用户名称'>
                    <Input placeholder='请输入用户名称' />
                </Form.Item>
                <Form.Item name='state' label='订单状态'>
                    <Select style={{ width: 120 }}>
                        <Select.Option value={0}>所有</Select.Option>
                        <Select.Option value={1}>进行中</Select.Option>
                        <Select.Option value={2}>已完成</Select.Option>
                        <Select.Option value={3}>超时</Select.Option>
                        <Select.Option value={4}>取消</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Button type='primary' className='mr10' onClick={search.submit}>搜索</Button>
                    <Button type='default' onClick={search.reset}>重置</Button>
                </Form.Item>
            </Form>
            <div className="table">
                <div className="header">
                    <div className="title">订单管理</div>
                    <div className="action">
                        <Button type='primary' onClick={handleCreate}>新增</Button>
                        <Button type='primary' onClick={handleDownload}>下载</Button>
                    </div>
                </div>
                <Table
                    bordered
                    rowKey='_id'
                    columns={columns}
                    {...tableProps}
                />
            </div>
            <CreateOrder ref={orderRef} update={search.submit} />
            <OrderMarker ref={markerRef} update={search.submit} />
            <OrderRoute ref={routeRef} update={search.submit} />
        </>
    )
}